<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/8/31
 * Time: 11:41
 */

namespace Rain\Admin\Services\Business\Common;

trait Unified
{
    private static $config;

    /**
     * 成功回调
     *
     * @param string $msg
     * @return string
     */
    private function success($msg = ''){
        return $msg ? : $msg = '请求成功';
    }

    /**
     * 失败回调
     *
     * @param $code
     * @param mixed ...$msg
     * @return mixed|string
     */
    private function error($code, ...$msg){
        $message = getErrorMessage($code, self::getErrorConfig(), 'admin');

        return $msg ? sprintf($message, ...$msg) : $message;
    }

    /**
     * 返回数据
     *
     * @param $code
     * @param $msg
     * @param array $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function returnData($code, $msg = '', $data = []){
        if($code != 500) $msg = 200 == $code ? $this -> success($msg) : $this -> error($code, $msg);

        return response() -> json(echoArr($code, $msg, $data), 200);
    }

    /**
     * 获取错误配置
     *
     * @return \Illuminate\Config\Repository|mixed
     */
    protected static function getErrorConfig(){
        if(!self::$config) self::$config = config('error');

        return self::$config;
    }
}
